import { createStore, useStore as useVuexStore } from 'vuex'
import type { Store } from 'vuex'
import type { IRootState, IStoreType } from './types'

import login from './login/login'
import system from './main/system/system'

import { getPageListData } from '@/service/main/system/system'
import dashboard from './main/analysis/dashboard'

const store = createStore<IRootState>({
  state() {
    return {
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    }
  },
  getters: {},
  mutations: {
    // 保存数据
    changeEntireDepartment(state, entireDepartment) {
      state.entireDepartment = entireDepartment
    },
    changeEntireRole(state, entireRole) {
      state.entireRole = entireRole
    },
    changeEntireMenu(state, entireMenu) {
      state.entireMenu = entireMenu
    }
  },
  actions: {
    async getInitialDataAction({ commit }) {
      // 请求部门/角色数据
      const deptResult = await getPageListData('/department/list', { offset: 0, size: 1000 })
      const { list: deptList } = deptResult.data
      const roleResult = await getPageListData('/role/list', { offset: 0, size: 1000 })
      const { list: roleList } = roleResult.data
      const menuResult = await getPageListData('/menu/list', {})
      const { list: menuList } = menuResult.data

      // 保存
      commit('changeEntireDepartment', deptList)
      commit('changeEntireRole', roleList)
      commit('changeEntireMenu', menuList)
    }
  },
  modules: {
    login,
    system,
    dashboard
  }
})

export function setupStore(): void {
  store.dispatch('login/loadLocalLogin')
}

export function useStore(): Store<IStoreType> {
  return useVuexStore()
}

export default store
